package com.heima.redisson.demo;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 分布式锁Demo
 *
 * @author Fuqiang
 * @since :2023-04-02
 */
@Slf4j
@Component
public class RedissonDemo {

    @Autowired
    RedissonClient redissonClient;

    @Scheduled(cron = "*/3 * * * * ?")
    public void demo() {
        RLock lock = redissonClient.getLock("redisson-demo");
        // 加锁, 看门狗
        boolean isLocked = lock.tryLock();
        try {
            if (isLocked) {
                log.info("获取到锁, 开始执行业务逻辑");
                Thread.sleep(5000);
                log.info("业务逻辑执行完成");
            } else {
                return;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (isLocked) {
                log.info("锁被释放");
                lock.unlock();
            }
        }
    }

}
